import { ref } from 'vue'
import { useRoute, onBeforeRouteUpdate, useRouter } from 'vue-router';
import { useCookies } from '@vueuse/integrations/useCookies'

export function useTabList() {

    const route = useRoute()
    const router = useRouter()
    const cooike = useCookies()
    const activeTab = ref(route.path)
    const tabList = ref([
        {
            title: '后台首页',
            path: '/',
        }
    ])
    // 初始化标签导航
    initTabList()

    // 添加标签导航
    function addTab(tab) {
        console.log(tab);
        let newTab = tabList.value.findIndex
            (item => item.path == tab.path) == -1
        if (newTab) {
            tabList.value.push(tab)
        }
        cooike.set('tabList', tabList.value)

    }

    // 监听路由变化
    onBeforeRouteUpdate((to, from) => {
        activeTab.value = to.path
        addTab(
            {
                title: to.meta.title,
                path: to.path
            })
    })
    const changeTab = (e) => {
        activeTab.value = e
        router.push(e)

    }
    // 初始化标签导航
    function initTabList() {
        let tabs = cooike.get('tabList')
        if (tabs) {
            tabList.value = tabs
        }

    }
    // 关闭当前导航
    const removeTab = (e) => {
        // 检测事件触发
        console.log(e);
        let tabs = tabList.value
        let activeIndex = activeTab.value
        if (activeIndex == e) {
            tabs.forEach((item, index) => {
                if (item.path == e) {
                    const nextTab = tabs[index + 1] || tabs[index - 1]
                    if (nextTab) {
                        activeIndex = nextTab.path
                    }
                }
            }
            )
        }
        activeTab.value = activeIndex
        tabList.value = tabList.value.filter(item => item.path != e)
        cooike.set('tabList', tabList.value)

    }
    // 监听下拉菜单
    const handleClick = (e) => {
        console.log(e);
        if (e == 'clearAll') {
            // 清除其他标签
            activeTab.value = '/';
            tabList.value = [{
                title: '后台首页',
                path: '/',
            }
            ]
        }
        else if (e == 'clearOther') {
            // 过滤只剩下首页和当前激活的
            tabList.value = tabList.value.filter(item => item.path == '/' || item.path == activeTab.value)

        }
        cooike.set('tabList', tabList.value)
    }

    return {
        handleClick,
        removeTab,
        changeTab,
        tabList,
        activeTab
    }
}